<?php

namespace app\common\service\api;
use app\common\service\member\SettingService as MemberSetting;
use app\common\service\setting\Exception;
use app\common\service\system\SettingService;
use app\common\service\file\MerchantFileService;
use finfo;
use think\facade\Filesystem;
use think\File;
use thirdsdk\Http;

/**
 * 淘测测接口
 */
class TaoceSdkService
{
    const url = 'http://www.taoyanhao.com';

    /**
     * 淘测测验号
     * @Author: 易军辉
     * @DateTime:2024-08-07 18:12
     */
    public static function searchPlus($account='')
    {
        $method = "/Api/Rest.ashx?type=xinyu";
        $result = array(
            'code'=>400,
            'msg'=>'系统繁忙，请稍后再试',
            'data'=>null,
        );
        if(!$account){
            return $result;
        }
        $memberSetting = MemberSetting::info('is_account_register_verification');
        if($memberSetting['is_account_register_verification'] == 1){
            //获取token
            $sysSetting = SettingService::info('tao_uid,tao_secret_key');
            if(!isset($sysSetting['tao_uid']) || !isset($sysSetting['tao_secret_key']) || !$sysSetting['tao_uid'] || !$sysSetting['tao_secret_key']){
                $result['msg'] = "请配置淘测测接口参数";
                return $result;
            }
            $ticks = time()* 1000;
            $token = md5($sysSetting['tao_uid'].$ticks.$account.$sysSetting['tao_secret_key']);

            $http = new Http('taoceSearchPlus');
            $api_res  = $http->get(self::url.$method."&uid=".$sysSetting['tao_uid']."&ticks=".$ticks."&nick=".$account."&token=".$token);
            if($api_res){
                $result['code'] =200;
                $result['msg'] ='查询成功';
                $result['data'] = $api_res['data'];
            }
        }else{
            $result['code'] = 401;
            $result['msg'] = '未开启买号绑定时是否验号';
        }
        return $result;
    }
    public static function getGoods()
    {

    }


    public static function information($param)
    {
        //type 1:淘宝 2:京东 3:拼多多 4:抖音 5:天猫 6:阿里巴巴
        $data = ['goods_id' => "",'goods_name' => "","goods_pic" =>"","goods_price" =>"","file_id" =>""];
        try {
            $timestamp = round(microtime(true) * 1000);
            $parsed_url = parse_url($param['parsed_url']);
            if(isset($parsed_url['query'])){
                $query_str = $parsed_url['query'];
            }else{
                $query_str = "";
            }


            // 解析查询字符串到数组
            parse_str($query_str, $query_params);
            $itemid = "";
            $sysSetting = SettingService::info('tao_uid,tao_secret_key');

            $uid = $sysSetting['tao_uid'];
            $secret = $sysSetting['tao_secret_key'];
            $type = "";
            $curl = curl_init();
            $link = self::url."/Api/Rest.ashx?uid=".$uid."&ticks=".$timestamp;
            switch ($param['type']) {
                case 5:
                    $type = "ItemPicTitle";
                    $itemid = $query_params['id'];
                case 1:
                    $type = "ItemPicTitle";
                    $itemid = $query_params['id'];
                    break;
                case 3:
                    $type = "PddItemSimpleInfo";
                    $itemid = $query_params['goods_id'];
                    break;
                case 2:
                    $type = "JdItemSimpleInfo";
                    $lastPos = strrpos($param['parsed_url'], "/");
                    $position = strrpos($param['parsed_url'],".html");
                    $itemid = substr($param['parsed_url'], $lastPos+1, $position-$lastPos-1);
                    break;
                case 6:
                    $type = "alibabaItemSimpleInfo";
                    $itemid = $query_params['offerId'];
                    break;
                case 4:
                    $type = "DyItemSimpleInfo";
                    $itemid = $query_params['id'];
                    break;
            }
            if(!$itemid){
                exception('未获取到商品ID');
            }
            $token = md5($uid.$timestamp.$itemid.$secret);
            $link = $link . "&type=".$type."&token=".$token."&itemid=".$itemid;
            $http = new Http('taoceSearchPlus');
            $response  = $http->get($link);
//             var_dump($response);exit();
//             exit();
//             curl_setopt_array($curl, array(
//                 CURLOPT_URL => $link,
//                 CURLOPT_RETURNTRANSFER => true,
//                 CURLOPT_CUSTOMREQUEST => 'GET'
//             ));
//             $response = curl_exec($curl);
//             curl_close($curl);
//             $response = json_decode($response, true);

            switch ($param['type']) {
                case 3:
                    $data['goods_id'] = $response['data']["goods_id"];
                    $data['goods_pic'] = $response['data']["goods_pic"];
                    $data['goods_price'] = str_replace("￥", "", $response['data']["min_on_sale_group_price"]);
                    $data['goods_name'] = $response['data']["goods_name"];
                    break;
                case 5:
                case 1:
                case 6:
                    $data['goods_id'] = $response['data']["itemid"];
                    $data['goods_pic'] = $response['data']["img"];
                    $data['goods_price'] = $response['data']["price"];
                    $data['goods_name'] = $response['data']["title"];
                    break;
                case 2:
                    $data['goods_id'] = $response['data']["itemId"];
                    $data['goods_pic'] = $response['data']["img"];
                    $data['goods_price'] = $response['data']["price"];
                    $data['goods_name'] = $response['data']["title"];
                    break;
                case 4:
                    break;
            }
//            $data['goods_pic'] = "https://gju1.alicdn.com/tps/i2/1637911651/O1CN01gomUDg1O4CrjBsU8v_!!0-item_pic.jpg";
            $file['file_url'] = $data['goods_pic'];
            $file['type'] = 'url';
            /*****************下载远程图片********************/
            if(isset($data['goods_pic'])){
                // 下载图片并存储到临时文件
                $fileContent = file_get_contents($data['goods_pic']); // 获取图片内容
                if ($fileContent !== false) {
                    // 获取文件的 MIME 类型
                    $finfo = new finfo(FILEINFO_MIME_TYPE);
                    $mimeType = $finfo->buffer($fileContent);
                    $fileExt = 'jpg';  // 默认扩展名

                    // 根据 MIME 类型推测文件扩展名
                    switch ($mimeType) {
                        case 'image/jpeg':
                            $fileExt = 'jpg';
                            break;
                        case 'image/png':
                            $fileExt = 'png';
                            break;
                        case 'image/gif':
                            $fileExt = 'gif';
                            break;
                        case 'image/webp':
                            $fileExt = 'webp';
                            break;
                    }

                    // 将文件保存到 public/storage 目录
                    $fileName = uniqid('img_').time();
                    $file_path ='storage/merchant'.mer_id().'/file/'.date('Ymd');
                    $filePath = public_path($file_path); // 你可以调整存储路径
                    // 检查目录是否存在
                    if (!file_exists($filePath)) {
                        // 如果不存在，则尝试创建目录
                        // 第二个参数是可选的模式，默认为0777，第三个参数recursive设为true可以创建多级目录
                        if (!mkdir($filePath, 0755, true)) {
                            error('无法创建目录，请联系管理员');
                        }
                    }
                    // 保存图片到临时文件
                    file_put_contents($filePath.$fileName. '.' . $fileExt, $fileContent);
                    $data1 = MerchantFileService::addByPath($fileName,($file_path."/".$fileName. '.' . $fileExt),$fileExt);
                    if(isset($data1['file_url'])){
                        $data['goods_pic'] =$data1['file_url'];
                    }
                }
            }else{
                $data1 = MerchantFileService::add($file);
            }
            $data['file_id'] = $data1['file_id'];
            return $data;
        }catch (\Exception $e) {
            exception($e->getMessage());
//            var_dump($e->getMessage());exit();
            return $data;
        }

    }
}
